﻿import $ from 'jquery'
//文件下载对象
export function FileDownloader(fileLoc, mgr)
{
    var _this = this;
    this.ui = {idProcSave:-1, msg: null, process: null, percent: null, btn: {del:null,cancel:null,down:null,stop:null,open:null,openFd:null},div:null};
    this.app = mgr.app;
    this.Manager = mgr;
    this.Config = mgr.Config;
    this.data = $.extend({}, mgr.data, {ui:mgr.ui});
    this.fields = $.extend(true,{}, mgr.Config.Fields, fileLoc.fields);//每一个对象自带一个fields幅本
    this.State = this.data.state.None;
    this.event = mgr.event;
    this.fileSvr = {
          id:""//guid
        , uid: 0
        , ip: ""//客户端IP
        , nameLoc: ""//自定义文件名称
        , folderLoc: this.Config["Folder"]
        , pathLoc: ""
        , fileUrl:""
        , lenLoc: 0
        , perLoc: "0%"
        , lenSvr: 0
        , sizeSvr:"0byte"
        , complete: false
        , fdTask: false
    };
    $.extend(true,this.fileSvr, fileLoc);//覆盖配置

    this.hideBtns = function ()
    {
        $.each(this.ui.btn, function (i, n)
        {
            $(n).hide();
        });
    };

    //方法-准备
    this.ready = function ()
    {
        this.ui.btn.del.click(function () { _this.remove(); });
        this.ui.btn.stop.click(function () { _this.stop(); });
        this.ui.btn.down.click(function () { _this.down(); });
        this.ui.btn.cancel.click(function () { _this.remove(); });
        this.ui.btn.open.click(function () { _this.openFile(); });
        this.ui.btn.openFd.click(function () { _this.openPath(); });

        this.hideBtns();
        this.ui.btn.down.show();
        this.ui.btn.cancel.show();
        this.ui.ico.file.attr("src", this.data.ui.tmp.ico.file_wait);
        this.ui.msg.text("正在下载队列中等待...");
        this.ui.size.text(this.fileSvr.sizeSvr);
        this.ui.process.css("width", this.fileSvr.perLoc);
        this.ui.percent.text("(" + this.fileSvr.perLoc + ")");
        this.Manager.queueWait.push(this.fileSvr.id);//添加到等待队列
        this.State = this.data.state.Ready;
        this.svr_create();//添加到服务器
    };

    this.addQueue = function ()
    {
        this.app.addFile(this.fileSvr);
    };

    //方法-开始下载
    this.down = function ()
    {
        this.Manager.add_work(this.fileSvr.id);
        this.hideBtns();
        this.ui.btn.stop.show();
        this.ui.msg.text("开始连接服务器...");
        this.ui.ico.file.attr("src", this.data.ui.tmp.ico.file_down);
        this.State = this.data.state.Posting;
        this.Manager.remove_wait(this.fileSvr.id);
        this.app.downUrl(this.fileSvr);//下载队列
    };

    //方法-停止传输
    this.stop = function ()
    {
        this.hideBtns();
        //this.SvrUpdate();
        this.State = this.data.state.Stop;
        this.ui.msg.text("下载已停止");
        this.app.stopFile(this.fileSvr);
        this.Manager.del_work(this.fileSvr.id);//从工作队列中删除
    };

    this.remove = function ()
    {
        this.app.stopFile(this.fileSvr);
        //从上传列表中删除
        this.ui.div.remove();
        this.Manager.remove_wait(this.fileSvr.id);
        this.Manager.remove_url(this.fileSvr.fileUrl);
        this.svr_delete();
    };

    this.openFile = function ()
    {
        this.app.openFile(this.fileSvr);
    };

    this.runFile = function () {
        this.app.runFile(jQuery.extend({}, this.fileSvr, {pars:"-s"} ) );
    };

    this.openPath = function () {
        this.app.openPath(this.fileSvr);
    };

    //在出错，停止中调用
    this.svr_update = function ()
    {
        if (!this.Config.DataBase) return;//

        var param = jQuery.extend({}, this.fields, {
            time: new Date().getTime()
            , id: this.fileSvr.id
            , lenLoc: this.fileSvr.lenLoc
            , perLoc: this.fileSvr.perLoc
            , nameLoc: encodeURIComponent(this.fileSvr.nameLoc)
            , pathLoc: encodeURIComponent(this.fileSvr.pathLoc)
            , lenSvr: this.fileSvr.lenSvr
            , sizeSvr: this.fileSvr.sizeSvr
        });
        $.ajax({
            type: "GET"
            , dataType: 'jsonp'
            , jsonp: "callback" //自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名
            , url: _this.Config["UrlUpdate"]
            , data: param
            , success: function (msg) { }
            , error: function (req, txt, err) { alert("更新下载信息失败！" + req.responseText); }
            , complete: function (req, sta) { req = null; }
        });
    };

    //在服务端创建一个数据，用于记录下载信息，一般在HttpDownloader_BeginDown中调用
    this.svr_create = function ()
    {
        if (!this.Config.DataBase) return;//
        //续传则不记录
        if (this.fileSvr.lenLoc>0) return;
        var param = jQuery.extend({}, this.fields, {file:encodeURIComponent(JSON.stringify(this.fileSvr)), time: new Date().getTime() });

        $.ajax({
            type: "GET"
            , dataType: 'jsonp'
            , jsonp: "callback" //自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名
            , url: _this.Config["UrlCreate"]
            , data: param
            , success: function (msg)
            {
                if (msg.value == null) return;
            }
            , error: function (req, txt, err) { alert("创建信息失败！" + req.responseText); }
            , complete: function (req, sta) { req = null; }
        });
    };

    this.isComplete = function () { return this.State == this.data.state.Complete; };
    this.svr_delete = function ()
    {
        if (!this.Config.DataBase) return;//
        var param = jQuery.extend({}, this.fields, { id: this.fileSvr.id, time: new Date().getTime() });
        $.ajax({
            type: "GET"
            , dataType: 'jsonp'
            , jsonp: "callback" //自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名
            , url: _this.Config["UrlDel"]
            , data: param
            , success: function (json){}
            , error: function (req, txt, err) { alert("删除数据错误！" + req.responseText); }
            , complete: function (req, sta) { req = null; }
        });
    };

    this.down_complete = function ()
    {
        this.Manager.filesCmp.push(this);
        this.Manager.del_work(this.fileSvr.id);//从工作队列中删除
        this.Manager.remove_wait(this.fileSvr.id);
        this.Manager.remove_url(this.fileSvr.fileUrl);
        this.hideBtns();
        this.event.downComplete(this);//biz event
        this.ui.process.css("width", "100%");
        this.ui.percent.text("(100%)");
        this.ui.msg.text("下载完成");
        this.ui.btn.open.show();
        this.ui.btn.openFd.show();
        this.ui.ico.file.attr("src", this.data.ui.tmp.ico.file_ok);
        this.State = this.data.state.Complete;

        this.svr_delete();
        setTimeout(function () { _this.Manager.down_next(); }, 500);
    };

    this.down_recv_size = function (json)
    {
        this.ui.size.text(json.size);
        this.fileSvr.sizeSvr = json.size;
        this.fileSvr.lenSvr = json.len;
    };

    this.down_recv_name = function (json)
    {
        this.hideBtns();
        this.ui.btn.stop.show();
        this.ui.name.text(json.nameSvr);
        this.ui.name.attr("title", json.nameSvr);
        this.fileSvr.pathLoc = json.pathLoc;
        if (this.fileSvr.nameLoc.length < 1) this.fileSvr.nameLoc = json.nameSvr;
    };

    this.query_end = function (json)
    {
        this.ui.size.text(json.sizeSvr);
        this.fileSvr.sizeSvr = json.sizeSvr;
        this.fileSvr.lenSvr = json.lenSvr;
        this.fileSvr.pathLoc = json.pathLoc;
        this.fileSvr.nameLoc = json.nameLoc;
        this.ui.name.text(json.nameLoc);
        this.ui.name.attr("title", json.nameLoc);
        this.svr_update();
    };

    this.down_process = function (json)
    {
        this.fileSvr.lenLoc = json.lenLoc;//保存进度
        this.fileSvr.perLoc = json.percent;
        this.fileSvr.sizeSvr = json.lenRecv;
        this.ui.percent.text("("+json.percent+")");
        this.ui.process.css("width", json.percent);
        this.ui.ico.file.attr("src", this.data.ui.tmp.ico.file_dec);
        var msg = [json.lenRecv, " ", json.speed, " ", json.time, " ", json.elapsed];
        this.ui.msg.text(msg.join(""));
        //通知事件
        this.event.downProcess(this);
    };
    
    this.down_begin = function (json)
    {
        this.startProcSave();
    };

    this.down_error = function (json)
    {
        this.stopProcSave();
        this.hideBtns();
        this.ui.btn.down.show();
        this.ui.btn.del.show();
        this.event.downError(this, json.code);//biz event
        this.ui.msg.text(this.data.errCode[json.code+""]);
        this.ui.ico.file.attr("src", this.data.ui.tmp.ico.file_err);
        this.State = this.data.state.Error;
        this.svr_update();
        this.Manager.del_work(this.fileSvr.id);//从工作队列中删除
        this.Manager.add_wait(this.fileSvr.id);

        //自动重连
        if(this.Config.AutoConnect.opened)
        {            
            setTimeout(function()
            {
                if( _this.State == _this.data.state.Posting) return;
                _this.down();
            },this.Config.AutoConnect.time);
        }
    };

    this.down_stoped = function (json)
    {
        this.stopProcSave();
        this.hideBtns();
        this.ui.btn.down.show();
        this.ui.btn.del.show();
        this.ui.ico.file.attr("src", this.data.ui.tmp.ico.file_wait);
        this.svr_update();
        //通知事件
        this.event.downStoped(this);
    };

    this.startProcSave=function(){
        this.ui.idProcSave = setInterval(function(){
            _this.svr_update();
        },this.Config.ProcSaveTm * 1000);

    };
    this.stopProcSave=function(){
        if(-1 != this.ui.idProcSave) clearInterval(this.ui.idProcSave);
    };
}